import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo } from '@/api/user'
import { LoginFormData, LoginResponseData } from '@/api/user/type'
import { UserState } from './types/type'

const userStore = defineStore('user', {
  state: (): UserState => ({
    token: localStorage.getItem('TOKEN'),
    userInfo: JSON.parse(window.sessionStorage.getItem('userInfo') || '[]'),
  }),
  actions: {
    async login(data: LoginFormData) {
      const result: LoginResponseData = await reqLogin(data)
      if (result.code === 200) {
        this.token = result.data
        localStorage.setItem('TOKEN', this.token)
        return Promise.resolve(result)
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    async getUserInfo() {
      let res = await reqUserInfo()
      if (res.code === 200) {
        this.userInfo = res.data
        window.sessionStorage.setItem('userInfo', JSON.stringify(res.data))
      }
    },

    logout() {
      this.userInfo = null
      this.token = null
      localStorage.removeItem('TOKEN')
    },
  },
  getters: {},
})

export default userStore
